package com.zhu.controller;

import com.zhu.pojo.Result;
import com.zhu.pojo.User;
import com.zhu.service.UserService;
import com.zhu.utils.JWTutil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import static com.zhu.utils.AESutil.decrypt;
import static com.zhu.utils.AESutil.encrypt;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    @CrossOrigin
    public Result login(@RequestBody User user){
        String pw = user.getPassword();
        User user1 = userService.login(user);
        if(pw==null) return Result.fail("该用户名还未创建用户");
        String ppw = encrypt(pw);
        if(!ppw.equals(user1.getPassword())) return Result.fail("密码错误，请重试");
        user1.setToken(JWTutil.createToken());
        return Result.ok(user1);
        //return Result.ok();
    }

    @PostMapping("/register")
    public Result register( @RequestBody User user){
        String pw ;
        User user1= userService.login(user);
        pw = user1.getPassword();
        if(pw!=null) return Result.fail("该用户已被创建");
        String pattern = "^(?=.*[A-Za-z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$";
        if(user.getPassword().matches(pattern)){
            String newPass = encrypt(user.getPassword());
            user.setPassword(newPass);
            userService.register(user);
            return Result.ok();
        }
        return Result.fail("密码格式不正确");
    }

    @PostMapping("/getinfo")
    public Result getinfo(@RequestBody int id){
        return Result.ok(userService.getinfo(id));
    }

}
